package pkg

import (
	"bytes"
	"context"
	"github.com/qiniu/go-sdk/v7/storagev2/credentials"
	"github.com/qiniu/go-sdk/v7/storagev2/http_client"
	"github.com/qiniu/go-sdk/v7/storagev2/uploader"
	"io"
	"mime/multipart"
	"monment/basic/config"
)

func QiNiuYun(file *multipart.FileHeader) (string, error) {
	accessKey := config.AppCfg.QiNiuYun.AccessKey
	secretKey := config.AppCfg.QiNiuYun.SecretKey
	mac := credentials.NewCredentials(accessKey, secretKey)
	bucket := config.AppCfg.QiNiuYun.Bucket
	key := file.Filename
	uploadManager := uploader.NewUploadManager(&uploader.UploadManagerOptions{
		Options: http_client.Options{
			Credentials: mac,
		},
	})

	fileStr, _ := file.Open()
	buf := &bytes.Buffer{}
	_, err := io.Copy(buf, fileStr)
	if err != nil {
		return "", nil
	}
	reader := bytes.NewReader(buf.Bytes())
	err = uploadManager.UploadReader(context.Background(), reader, &uploader.ObjectOptions{
		BucketName: bucket,
		ObjectName: &key,
		CustomVars: map[string]string{
			"name": "github logo",
		},
		FileName: key,
	}, nil)

	return config.AppCfg.QiNiuYun.URL + key, err

}
